package com.lzc.websocket;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.lzc.mapper.FriendMapper;
import com.lzc.mapper.MessageMapper;
import com.lzc.pojo.entity.Friend;
import com.lzc.pojo.entity.Message;
import javafx.scene.input.DataFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.datetime.standard.DateTimeFormatterFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.websocket.Session;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.List;

import static com.lzc.websocket.WebSocketListener.sessions;

@Component
public class MessageHandler {

    @Autowired
    private FriendMapper friendMapper;

    @Autowired
    private MessageMapper messageMapper;

    // 私聊处理
    public void singChat(MessageCommand command){

        Session sourceSession = sessions.get(command.getSid());

        // 判断是否是好友
        if (!isFriend(command.getSid(),command.getRid())){
            // 不是好友返回失败消息
            command.setContext("对方不是你的好友");
            String commandStr = JSONUtil.toJsonStr(command);
            // 返回失败消息
            sourceSession.getAsyncRemote().sendText(commandStr);
            // 保存消息记录到数据库
            Message message = commandTextToMessage(command, (byte) 0);
            messageMapper.insert(message);
            return;
        }

        // 获取接收者的session
        Session session = sessions.get(command.getRid());
        // 判断接受者是否存活
        if (session != null && session.isOpen()){

            Message message = commandTextToMessage(command, (byte) 1);
            messageMapper.insert(message);
            String messageStr = JSONUtil.toJsonStr(message);
            session.getAsyncRemote().sendText(messageStr);
            return;
        }

        // 保存消息记录到数据库
        // 对方不在线或在线都要保存记录到数据库
        Message message = commandTextToMessage(command, (byte) 1);
        messageMapper.insert(message);

    }


    /**
     * 判断是否是好友
     * @param sid 发生方
     * @param rid 接受方
     * @return
     */
    private boolean isFriend(Long sid, Long rid){
        Friend friend = friendMapper.isFriend(sid, rid);
        if (friend == null){
            return false;
        }
        return true;
    }

    /**
     * 普通发送消息转为 数据库消息存储
     */
    private Message commandTextToMessage(MessageCommand command,byte state){

        Message message = new Message();
        message.setContext(command.getContext());
        message.setCode(command.getCode());
        message.setSourceId(command.getSid());
        message.setTargetId(command.getRid());
        message.setSendTime(LocalDateTime.now());
        message.setState(state);
        return message;
    }
}
